package org.example;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 1060785272@qq.com
 * @version 1.0
 * @description: TODO
 * @date 2022-4-10 下午 9:56
 */
@Aspect
@Component
@Order(1)
public class PermissionFirstAdvice {
    // 定义一个切面，括号内写入第1步中自定义注解的路径
    @Pointcut("@annotation(org.example.PermissionAnnotation)")
    private void permissionCheck() {
    }

    @Before("permissionCheck()")
    public void beforeAdvice(JoinPoint joinPoint) {
        System.out.println("@Before(\"permissionCheck()\")");
        // 这里只是一个示例，你可以写任何处理逻辑
        System.out.println("---------Before触发了----------");
        // 获取签名
        Signature signature = joinPoint.getSignature();
        // 获取切入的包名
        String declaringTypeName = signature.getDeclaringTypeName();
        System.out.println("declaringTypeName:" + declaringTypeName);
        // 获取即将执行的方法名
        String funcName = signature.getName();
        System.out.println("funcName:" + funcName);

        // 也可以用来记录一些信息，比如获取请求的 URL 和 IP
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 获取请求 URL
        String url = request.getRequestURL().toString();
        System.out.println("url:" + url);
        // 获取请求 IP
        String ip = request.getRemoteAddr();
        System.out.println("ip:" + ip);

        Object[] objects = joinPoint.getArgs();
        System.out.println("参数是：" + objects);
    }

    @Around("permissionCheck()")
    public Object permissionCheckFirst(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("---------Around触发了----------");
        //获取请求参数，详见接口类
        Object[] objects = joinPoint.getArgs();
//        调用目标方法并返回相应结果
        Object proceed = joinPoint.proceed(objects);
        return proceed;
    }


    @AfterReturning(pointcut = "permissionCheck()", returning = "result")
    public void afterReturningAdvice(JoinPoint joinPoint, Object result) {
        System.out.println("---------AfterReturning触发了----------");
    }

    @AfterThrowing(pointcut = "permissionCheck()", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Throwable ex) {
        System.out.println("@AfterThrowing(pointcut = \"permissionCheck()\", throwing = \"ex\")");
    }

    @After("permissionCheck()")
    public void afterAdvice(JoinPoint joinPoint) {
        System.out.println("@After(\"permissionCheck()\")");
    }
}

